//package com.xiaozhen.gateway.filter;
//
//import com.xiaozhen.common.core.constant.SecurityConstants;
//import com.xiaozhen.common.core.constant.UserConstants;
//import com.xiaozhen.common.core.exception.CustomException;
//import com.xiaozhen.common.core.utils.ServletUtils;
//import com.xiaozhen.common.core.utils.StringUtils;
//import com.xiaozhen.gateway.utils.RSAUtil;
//import io.jsonwebtoken.Claims;
//import io.jsonwebtoken.ExpiredJwtException;
//import io.jsonwebtoken.Jwts;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.http.HttpMethod;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.http.server.reactive.ServerHttpResponse;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * HISTORY
// *
// * @author zhenweisheng
// * @date 2021/8/9 10:58
// * @description:
// */
//@Component
//public class AuthFilter implements GlobalFilter, Ordered {
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpRequest.Builder mutate = request.mutate();
//        String url = request.getURI().getPath();
//        //放行白名单
//        if ("/xiaozhen-auth/oauth/token".equals(url)) {
//            //放行
//            return chain.filter(exchange.mutate().request(mutate.build()).build());
//        }
//        String token = getToken(request);
//        if (StringUtils.isNotBlank(token)) {
//            try {
//                Claims jwt = getTokenBody(token);
//                // 设置用户信息到请求
//                Object userId = jwt.get(UserConstants.USER_HEADER);
//                addHeader(mutate, UserConstants.USER_HEADER, userId);
//                // 设置租户信息到请求
//                Object tenantId = jwt.get(UserConstants.TENANT_HEADER);
//                addHeader(mutate, UserConstants.TENANT_HEADER, tenantId);
//                // 根据resourceIds 判断可不可以访问相应资源
//                Object aud = jwt.get(SecurityConstants.TOKEN_RESOURCE_IDS);
//                if (aud != null) {
//                    List<String> resourceIds = (ArrayList) aud;
//                    String resourceId = url.substring(1, url.indexOf("/", 1));
//                    if (!resourceIds.contains(resourceId)) {
//                        throw new CustomException("没有该资源访问权限");
//                    }
//                }
//            } catch (ExpiredJwtException e) {
//                return returnAuthFail(exchange, "令牌已过期");
//            } catch (CustomException e) {
//                return returnResourceFail(exchange, e.getMessage());
//            } catch (Exception e) {
//                return returnResourceFail(exchange, "令牌签名验证失败");
//            }
//        }
//        //放行
//        return chain.filter(exchange.mutate().request(mutate.build()).build());
//    }
//
//    /**
//     * 获取请求token
//     */
//    private String getToken(ServerHttpRequest request) {
//        String token = request.getHeaders().getFirst(SecurityConstants.TOKEN_AUTHENTICATION);
//        return token;
//    }
//
//    private static Claims getTokenBody(String token) {
//        return Jwts.parser()
//                .setSigningKey(RSAUtil.getPublicKey())
//                .parseClaimsJws(token)
//                .getBody();
//    }
//
//    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
//        if (value == null) {
//            return;
//        }
//        String valueStr = value.toString();
//        String valueEncode = ServletUtils.urlEncode(valueStr);
//        mutate.header(name, valueEncode);
//    }
//
//    /**
//     * 返回资源权限校验失败
//     *
//     * @param exchange
//     * @return
//     */
//    private Mono<Void> returnResourceFail(ServerWebExchange exchange, String message) {
//        ServerHttpResponse serverHttpResponse = exchange.getResponse();
//        serverHttpResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
//        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
//        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
//        return exchange.getResponse().writeWith(Flux.just(buffer));
//    }
//
//    /**
//     * 返回校验失败
//     *
//     * @param exchange
//     * @return
//     */
//    private Mono<Void> returnAuthFail(ServerWebExchange exchange, String message) {
//        ServerHttpResponse serverHttpResponse = exchange.getResponse();
//        serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
//        String resultData = "{\"code\":\"401\",\"msg\":" + message + "}";
//        byte[] bytes = resultData.getBytes(StandardCharsets.UTF_8);
//        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
//        return exchange.getResponse().writeWith(Flux.just(buffer));
//    }
//
//    @Override
//    public int getOrder() {
//        return -200;
//    }
//}
